'''
Created on 06/04/2009

@author: Edward
'''
from im.ds import dsconstants, dsofactory
from im.event import eventconstants
from im.event.event import Event
from im.event.eventhandler import BaseEventHandler
from im.event.eventmanager import EventManager
import httplib
import datetime
import os

class HubErrorHandler(BaseEventHandler):
    def do(self, data):
        dso = data
        http_request = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_REQUEST).get_literal()
        lock = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_LOCK).get_literal()
        error_code = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_ERROR_CODE).get_literal()
        
        fault_message = None
        if error_code == httplib.NOT_FOUND:
            fault_message = "spear-im-not-active"
        elif error_code == httplib.REQUEST_TIMEOUT:
            fault_message = "hub-not-available"            
        else:
            print error_code
            fault_message = "unknown-hub-error"

        relative_path = "../../../pages/im/imerror.html"
        
        # get the html template
        template_path = os.path.join(os.path.dirname(__file__), relative_path)
        file = open(template_path)
        html_template_string = file.read()
        html_string = html_template_string.replace('${fault_message}', fault_message)
        new_dso = dsofactory.create_dso_for_im_http_response_handler(httplib.OK, 
                                                               'text/html', 
                                                               html_string, 
                                                               http_request, 
                                                               lock)
        event = Event(eventconstants.HTTP_RESPONSE_EVENT_TYPE, new_dso)
        EventManager().add_event(event)
        print 'End Request: ' + str(datetime.datetime.now())                       